<?php
require_once 'xs_sdk/lib/XS.php';

class Indexer {
    public function add($item) {
        $this->save($item, false);
    }

    public function update($item) {
        $this->save($item, true);
    }

    public function save($pattern, $update) {
        $xs = new XS('pattern');
        $index = $xs->index; // 获取 索引对象
        $doc = new XSDocument;

        // 设置基础数据
        $data = array(
            'pid' => $pattern['pid'],
            'title' => $pattern['title'],
            'content' => $pattern['title'],
            'picture' => $pattern['picture'],
            'picture_thumb' => $pattern['picture_thumb'],
            'weight' => $pattern['weight'],
            'height' => $pattern['height'],
            'widthheight' => $pattern['widthheight'],
            'widthlow' => $pattern['widthlow'],
            'no' => $pattern['no'],
            'component' => $pattern['component'],
            'series' => $pattern['series']
        );

        // 处理封板================= begin =========================
        $plates_out = [];
        $plates = json_decode($pattern['plates'], true);

        foreach ($plates as $plate) {
            if (count($plate) == 1) {
                $plates_out[] = $plate[0] . $plate[0];
            } else {
                $plates_out[] = implode(',', $plate);
            }
        }

        if (count($plates_out) > 0) {
            $data['sealing'] = implode("|", $plates_out);
        }
        // 处理封板=================== end ===========================

        // 设置属性
        $properties = $pattern['properties'];
        $property_strings = '';

        // 属性字段拼接
        if ($properties != null) {
            foreach ($properties as $property) {
                $json = json_decode($property['property_value'], true);
                $value = $json['value'];

                if (is_array($value)) {
                    $property_strings .= ' ' . implode(',', $value);
                } else {
                    $property_strings .= ' ' . $value;
                }
            }
        }

        $data['content'] .= 'all ' . $property_strings;

        $doc->setFields($data);

        try {
            if ($this->checkExists($pattern['pid'])) {
                $index->update($doc);//->flushIndex();
            } else {
                $index->add($doc);//->flushIndex();
            }
        } catch (Exception $e) {
            print_r($e);
        }

        return true;
    }

    /**
     * 判断索引是否存在
     * @param $pid
     */
    private function checkExists($pid) {
        $xs = new XS('pattern');
        $search = $xs->search;
        $search->setQuery('pid:' . $pid);
        $docs = $search->search();
        $search->setLimit(5);

        if ($search->lastCount) {
            return true;
        }

        return false;
    }
}
